<?php
namespace control;

// 模具领用归还
class moldReturnClass extends adIndexClass
{
	private const page        = 'moldReturn';                    # 权限
	private const table       = 'mold_return';                   # 数据表
	private const tableTarget = 'machining_send_order';          # 数据表
	private const title       = '模具领用归还';
	private const state       = ['草稿', '已归还'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "领用单号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'process'  => [
                        'name'  => '工序',
                        'width' => 100,
                    ],
                    'useStid'         => [
                        'name'  => '领用人',
                        'width' => 100,
                    ],
                    'code'          => [
                        'name'  => '模具编码',
                        'width' => 150,
                    ],
                    'name'          => [
                        'name'  => "模具名称",
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格',
                        'width' => 150,
                    ],
                    'initial'          => [
                        'name'  => '期初寿命',
                        'width' => 100,
                    ],
                    'yield'          => [
                        'name'  => '本次产量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'remaining'          => [
                        'name'  => '剩余寿命',
                        'width' => 100,
                    ],
                    'lendTime'          => [
                        'name'  => '借出时间',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'estimatedTime'          => [
                        'name'  => '预计归还时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'actualTime'          => [
                        'name'  => '实际归还时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号"   => text(array("name" => "orderNo")),
                    "工序"   => selectMultiple(["name" => "processId", 'table' => "process", 'sqlId' => 'id', 'sqlField' => 'name', 'where' => " coid = '" . self::$coid . "' ", 'class' => 'width200']),
                    "领用人" => selectMultiple(["name" => "useStid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    "模具编码"   => text(["name" => "moldCode"]),
                    "模具名称"   => text(["name" => "moldName"]),
                    "规格"   => text(["name" => "moldModel"]),
                ],
                [
                    "借出时间" => text(['name' => 'lendTime', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*入口页*/
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url      = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "return")) {
            $button .= spanButton([
                'fun'  => 'operate',
                'name' => '归还',
                'para' => [
                    'act'   => 'return',
                    'state' => '归还',
                ],
            ]);
        }
        // if ($this->power(self::page, "return")) {
        // 	$button .= spanButton([
        // 		'fun' => 'operate',
        // 		'name' => '取消归还',
        // 		'para' => [
        // 			'act' => 'return',
        // 			'state' => '取消归还',
        // 		]
        // 	]);
        // }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*列表*/
	public function homeSearch(): bool|string
	{
		$where = '';
		$equal = [
			'processId' => $this->post('processId'),
			'useStid'   => $this->post('useStid'),
			'state'     => $this->post('state'),
			'coid'      => self::$coid,
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
		];
		//生成子查询语句
		$targetWhere = search([
			"like" => [
				'code'  => $this->post('moldCode'),
				'name'  => $this->post('moldName'),
				'model' => $this->post('moldModel'),
			],
		]);
		if ($targetWhere) {
			$where .= " and mdid IN (SELECT id FROM `mold` WHERE 1=1 $targetWhere) ";
		}
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);

		if ($this->post('lendTime')) {
			$where .= self::timeComparison($this->post('lendTime'), 'time', 'lendTime');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		$url      = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate  = array(
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => [
					"title" => self::title . "详情",
					"click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . $this->get(
							'cla'
						) . "&fun=detail&id=" . $array['id'] . "')",
				],
			);
			$mold      = query('mold', " id = '$array[mdid]' ");
			$initial   = ($array['state'] === '草稿') ? $mold['mouldRemainingLife'] : $array['initial'];
			$remaining = $initial - $array['yield'];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'code':
                    case 'name':
                    case 'model':
                        $row[] = $mold[$key];
                        break;
                    case 'process':
                        $process   = query('process', " id = '$array[processId]' ", 'name');
                        $row[] = $process['name'];
                        break;
                    case 'yield':
                        $row[] = self::lostZero($array['yield'],'numPrecision');
                        break;
                    case 'useStid':
                        $row[] = self::findStaff($array['useStid']);
                        break;
                    case 'initial':
                        $row[] = $initial;
                        break;
                    case 'remaining':
                        $row[] = $remaining;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
		//返回
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	/**
	 * 编辑页
	 *
	 * @return string
	 */
    public function edit()
    {
        $id        = $this->post('id');
        $info      = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        $sourceBox = '请选择工序和模具';
        if (!static::isNull($info['id'])) {
            $where     = " coid = '" . self::$coid . "' AND processId = '$info[processId]' AND materialId In (SELECT materialId FROM `mold_portfolio_detail` WHERE orderId IN (SELECT id FROM `mold_portfolio` WHERE mdid = '$info[mdid]')) ";
            $sourceBox = selectMultiple(['name' => "sourceId[]", 'class' => 'text', 'value' => $info['sourceId'], 'where' => $where, 'table' => "machining_send_order", 'sqlId' => 'id', 'sqlField' => 'orderNo', 'multiple' => true, 'title' => '生产派工单号']);
        }
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . '工序' => selectMultiple(["name" => "processId", 'id' => 'processId', 'table' => "process", 'sqlId' => 'id', 'sqlField' => 'name', 'where' => " coid = '" . self::$coid . "' ", 'title' => '工序', 'value' => $info['processId'],]),
                    must . '领用人' => selectMultiple(["name" => "useStid", 'value' => $info['useStid'], 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '领用人']),
                ],
                [
                    must . '模具' => hidden(['name' => 'mdid', 'value' => $info['mdid']])
                        . '<span id="moldName">' . ($info['mdid'] ? query('mold', "id = '$info[mdid]'", 'name')['name'] : '未选择') . '</span>'
                        . "<span class='del-row-button' onclick=\"layer('{$this->get('cla')}', 'addTarget',{ 'processId': $('#processId').val() } )\" style='margin-left: 10px'>选择</span>",
                ],
                [
                    '关联订单号' => '<p id="sourceIdBox" style="width: 100%;">' . $sourceBox . '</p>',
                    must . '数量' => text(['name' => "num", 'other' => self::digitalFiltering('numPrecision'), 'class' => 'text', 'value' => self::lostZero($info['num'],'numPrecision'), 'title' => '数量']),
                ],
                [
                    must . '借出时间' => text(['name' => "lendTime", 'class' => 'text', 'value' => $info['lendTime'] ?: $this->time, 'laydate' => ['type' => 'datetime'], 'title' => '借出时间']),
                    '预计归还时间' => text(['name' => "estimatedTime", 'class' => 'text', 'value' => $info['estimatedTime'], 'laydate' => ['type' => 'datetime'], 'title' => '预计归还时间']),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],

            ],
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $html .= <<<EOT
		<script>
		//选择明细
        function addTarget(){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addTargetEdit', $("form[name='mxForm']").serialize(), function(resp) {
	         if (resp.warn === 2){
	            $("[name='mdid']").val(resp.res.mdid);
	            $("#moldName").html(resp.res.name);
                $('#sourceIdBox').html(resp.res.sourceIdSel)
	         }else{
	             msg(resp.warn);
	         }
	        },'json');
        }
        
		</script>
EOT;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

	/**
	 *选择生产模具
	 *
	 * @return bool|string
	 */
	public function addTarget(): bool|string
	{
		$html   =
			select(["name" => "type", "title" => "分类", "option" => explode('，', para('moldType'))]) .
			text(["name" => "code", "title" => "模具编码"]) .
			text(["name" => "moldName", "title" => "模具名称"]) .
			text(["name" => "model", "title" => "规格型号"]) .
			hidden(['name' => 'processId', 'value' => $this->post('processId')]);
		$button = "<input style='margin-left: 5px' onclick=\"addTarget();$('#" . self::page . "AddTarget').hide()\" type='button' class='searchSub' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(["title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button]);
	}

	/**
	 *添加模具
	 */
	public function addTargetSearch(): bool|string
	{
		$where = search([
			"like" => [
				'name'  => $this->post('moldName'),
				'code'  => $this->post('code'),
				'model' => $this->post('model'),
			],
			"="    => [
				'type'  => $this->post('type'),
				'state' => '启用',
				'coid'  => self::$coid,
			],
			">"    => [
				'mouldRemainingLife' => 0,
			],
		]);
		$page  = $this->page([
			"table" => 'mold',
			"where" => $where,
			"order" => "time ASC",
		]);
		//获取表头
		$tr[] = ['', '分类', '模具编码', '模具名称', '规格型号'];
		//获取记录
		foreach ($page['array'] as $array) {
			$tr[] = array(
				"<input name='mxId' value='$array[id]' type='radio' class='radio-bigger'>",
				$array['type'],
				$array['code'],
				$array['name'],
				$array['model'],
			);
		}
		$json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                hidden(['name' => 'processId', 'value' => $this->post('processId')]) .
                $this->tableMany(array("tr" => $tr)) .
            "</form>" .
            $page['button']
        ;
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addTargetEdit(): bool|string
	{
		$mdid      = $this->post('mxId');
		$processId = $this->post('processId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mdid)) {
			$json['warn'] = '请选择模具';
		} elseif (empty($processId)) {
			$json['warn'] = '请选择工序';
		} else {
			$mold  = query('mold', "id = '$mdid' ");
			$where = " coid = '" . self::$coid . "' AND processId = '$processId' AND materialId In (SELECT materialId FROM `mold_portfolio_detail` WHERE orderId IN (SELECT id FROM `mold_portfolio` WHERE mdid = '$mdid')) ";
			$json  = [
				'warn' => 2,
				'res'  => [
					'name'        => $mold['code'] . '-' . $mold['name'] . '-' . $mold['model'],
					'mdid'        => $mold['id'],
					'sourceIdSel' => selectMultiple(['name' => "sourceId[]", 'class' => 'text', 'table' => "machining_send_order", 'where' => $where, 'sqlId' => 'id', 'sqlField' => 'orderNo', 'multiple' => true, 'title' => '生产派工单号']),
				],
			];
		}
		return json_encode($json, 320);
	}


	/**
	 * 编辑报错
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'processId'     => $this->post('processId'),
			'useStid'       => $this->post('useStid'),
			'mdid'          => $this->post('mdid'),
			'lendTime'      => $this->post('lendTime'),
			'estimatedTime' => $this->post('estimatedTime'),
			'num'           => $this->post('num'),
			'sourceId'      => $this->post('sourceId'),
			'text'          => $this->post('text'),
		];
		$annotation = [
			'processId'     => '工序',
			'useStid'       => '领用人',
			'mdid'          => '模具',
			'lendTime'      => '借出时间',
			'estimatedTime' => '预计归还时间',
			'num'           => '数量',
			'sourceId'      => '关联订单',
			'text'          => '备注',
		];
		$rules      = [
			'processId' => 'required',
			'useStid'   => 'required',
			'mdid'      => 'required',
			'lendTime'  => 'required',
			// 'estimatedTime' => 'required',
			'num'       => 'required',
			// 'sourceId'      => 'required',
			// 'text'          => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} else {
			$this->startTrans();
			$field['sourceId'] = $field['sourceId'] ? implode(',', $field['sourceId']) : '';
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'YRSQ' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'      => $id,
					'orderNo' => $orderNo,
					'coid'    => self::$coid,
					'state'   => '草稿',
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}

			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				// 更新模具数量
				self::upyield($id);
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			$mold = query('mold', " id = '$info[mdid]' ");
			//菜单
			$data = array(
				"id" => $info['id'],
			);
			//按钮
			$button[] = [
				"name" => "删除",
				"type" => "弹出层",
				"cla"  => $this->get('cla'),
				"fun"  => "operate",
				"post" => ["act" => 'del', "id" => $info['id']],
			];
			if ($info['state'] !== '已归还') {
				$button[] = [
					"name"  => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
					// 'style' => 'li-btn-blue-bg',
				];
				$button[] = [
					"name"  => "归还",
					"type"  => "弹出层",
					"title" => "归还",
					'cla'   => $this->get('cla'),
					'fun'   => 'operate',
					'post'  => [
						'id'    => $info['id'],
						'act'   => 'return',
						'state' => '归还',
					],
					'style' => 'li-btn-blue-bg',
				];
			}
			$mxtr[]   = ['订单编号', '产品编码', '产品名称', '规格型号', '单位', '订单数量', '良品数量', '不良品数量', '生产线', '下线时间'];
			$resIdArr = self::filterArray(explode(',', $info['sourceId']));
			$ids      = "'" . implode("','", $resIdArr) . "'";
			$result   = find(['table' => self::tableTarget, 'where' => " id IN ($ids) order by time"]);
			foreach ($result['array'] as $array) {
				$material    = query('material', " id = '$array[materialId]'");
				$line        = query('product_line', " id = '$array[lineId]' ", 'name')['name'];
				// 工序报工
				$mwhere        = generateWhere([
					'coid'          => self::$coid,
					'materialId' => $array['materialId'],
					'sendId'        => $array['id'],
					'state'         => '已确认',
				]);
				$yield         = static::total([
					'sql'   => " SELECT IFNULL(SUM(yield), 0) AS total FROM `process_report` WHERE 1=1 ",
					'where' => $mwhere,
				]);
				$badNum        = static::total([
					'sql'   => " SELECT IFNULL(SUM(badNum), 0) AS total FROM `process_report` WHERE 1=1 ",
					'where' => $mwhere,
				]);
				$processReport = query('process_report', $mwhere . ' ORDER BY endTime DESC', 'endTime');
				$mxtr[]        = [
					$array['orderNo'],
					$material['code'],
					$material['name'],
					$material['model'],
					$array['unit'],
					self::lostZero($array['num'],'numPrecision'),
					($yield != 0) ? self::lostZero($yield,'numPrecision') : '---',
					($badNum != 0) ? self::lostZero($yield,'numPrecision') : '---',
					$line,
					$processReport['endTime'],
				];
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				[
					[
						"工序"  => query('process', " id = '{$info['processId']}' ", 'name')['name'],
						"领用人" => self::findStaff($info['useStid']),
						"模具"  => $mold['code'] . ' - ' . $mold['name'] . ' - ' . $mold['model'],
						"数量" => $info['num'],
					],
					[
						"借出时间"   => $info['lendTime'],
						"预计归还时间" => $info['estimatedTime'],
						"实际归还时间" => $info['actualTime'],
					],
					[
						"备注" => pre($info['text']),
					],
				],
			]);
            $data['html'] .= $this->detailList([
                'title' => '关联订单',
                'html' => $this->listTable(array('tr' => $mxtr, 'showSort' => true)),
            ]);
            $data['html']   .= $this->tableShow(array(
                '系统信息'   => [
                    [
                        "单据编号" => $info['orderNo'],
                        "创建人"  => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                    ],
                ],
            ));
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	// 操作中转
	public function operate(): bool|string
	{
		$act    = $this->post('act') ?? '';
		$append = [];
		// 需要密码
		switch ($act) {
			case 'return':
				$act      = 'edit';
				$msg      = self::title . '修改状态';
				$function = 'changeState';
				$form     = self::page . 'OperateForm, listForm';
				$state    = $this->post('state');
				$power    = '';
				$title    = self::page . 'Return';
				if ($state == '归还') {
					$append = [
						must . '选择归还日期：' => text([
								"name"    => "actualTime",
								"title"   => "归还日期",
								'laydate' => ['type' => 'datetime'],
							]) . hidden(["name" => "state", 'value' => $state]) . space,
					];
				} else {
					$title  = self::page . 'Change';
					$append = [
						1 => hidden(["name" => "state", 'value' => $state]),
					];
				}
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'append'   => $append,
				'pwd'      => false,
				'word'     => false,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 修改状态
	 *
	 * @return bool|string
	 */
	public function changeState(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		$act   = 'edit';
		$json  = [];
		if (!$this->power(self::page, $act)) {
			$json['warn'] = "你没有此权限的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 修改field
			$fieldKey = 'state';
			$rawState = $this->post('state');
			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if ($info['id']) {
					if ($rawState == '归还') {
						if ($info['state'] == '已归还') {
							$text .= "ID【{$id}】，已是归还状态，无法归还" . '<br>';
							continue;
						}
						if (empty($this->post('actualTime'))) {
							$json['warn'] = '归还日期不能为空';
							goto resp;
						}elseif(strtotime($info['lendTime']) > strtotime($this->post('actualTime'))){
                            $json['warn'] = '归还日期不能小于借出时间';
                            goto resp;
                        }
					} elseif ($rawState == '取消归还') {
						if ($info['state'] == '待归还') {
							$text .= "ID【{$id}】，待归还状态，无法取消归还" . '<br>';
							continue;
						}
					}
					$fieldVlaue = ($info['state'] == '草稿') ? '已归还' : '待归还';
					// 修改状态
					$json['warn'] = static::update([
						"table" => self::table,
						'field' => [
							$fieldKey    => $fieldVlaue,
							'actualTime' => $this->post('actualTime') ? $this->post('actualTime') : '0',
						],
						"where" => $where,
					]);
					// 归还记录
					if ($json['warn'] == '更新成功' && $fieldVlaue == '已归还') {
						$mwhere    = " id = '$info[mdid]' ";
						$mold      = query('mold', $mwhere, 'mouldRemainingLife');
						$remaining = $mold['mouldRemainingLife'] - $info['yield'];
						// 调整模具剩余寿命
						static::update([
							'table' => 'mold',
							'field' => [
								'mouldRemainingLife' => $remaining,
							],
							'where' => " id = '$info[mdid]' ",
						]);
						// 修正归还申请表初始和剩余数量
						static::update([
							'table' => self::table,
							'field' => [
								'initial'   => $mold['mouldRemainingLife'],
								'remaining' => $remaining,
							],
							'where' => $where,
						]);
					}
					//添加记录
					$text .= "{$this->control['name']}变更" . self::title . "，ID【{$id}】,状态【{$fieldVlaue}】" . '<br>';
					$x++;
				}
			}
			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "操作了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}

		resp:
		return json_encode($json, 320);
	}

	// 获取模具产量
	public static function upyield($id)
	{
		$info = query(self::table, " id = '$id' ");
		if (!$info['sourceId']) {
			return;
		}
		$arr = self::filterArray(explode(',', $info['sourceId']));
		$ids = "'" . implode("','", $arr) . "'";
		// 产量
		$yield   = static::total([
			'sql'   => " SELECT IFNULL(SUM(yield), 0) AS total FROM `process_report` as p, `machining_send_order` as m WHERE m.id = p.sendId AND  m.id IN ($ids)  ",
			'where' => generateWhere([
				'p.state'     => '已确认',
				'p.processId' => $info['processId'],
				'p.coid'      => self::$coid,
			]),
		]);
		$initial = query('mold', " id = '$info[mdid]' ", 'mouldRemainingLife')['mouldRemainingLife'];
		// if ($initial - $yield < 0) {
		// 	return '模具寿命不足';
		// }
		static::update([
			'table' => self::table,
			'field' => [
				'initial'   => $initial,
				'yield'     => $yield,
				'remaining' => $initial - $yield,
			],
			'where' => " id = '$id'",
		]);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '已归还') {
					$warn = "删除失败：已归还，暂不能删除";
				} else {
					//最后删除基本参数
					delete(["table" => self::table, "where" => " id = '$id' "]);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}
}
